package com.toune.blackmusic.util;


import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.toune.blackmusic.activity.BaseActivity;
import com.vondear.rxtool.view.RxToast;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public abstract class NoHttpCallBack<T> implements OnResponseListener<String> {

    public static Map<String, Object> params = new HashMap<>();

    private Class<T> tClass;

    public NoHttpCallBack(Class<T> tClass) {
        this.tClass = tClass;
    }

    @Override
    public void onStart(int what) {
        handler.sendEmptyMessage(START);
    }

    @Override
    public void onFailed(int what, Response<String> response) {
        getFailed(response.get());
    }

    @Override
    public void onSucceed(int what, Response<String> response) {
        String json = response.get();
        if (tClass.isInstance(String.class)) {
            getSucceed((T) json);
            return;
        }
        if (!TextUtils.isEmpty(json)) {
            T t = GsonBinder.toObj(json, tClass);
            getSucceed(t);
        }
    }

    @Override
    public void onFinish(int what) {
        params.clear();
        handler.sendEmptyMessage(FINISH);
    }

    protected abstract void getSucceed(T t);

    protected void getFailed(String msg) {
        Message message = new Message();
        message.what = FAILED;
        message.obj = msg;
        handler.sendMessage(message);
    }


    public static final int START = 101;
    public static final int FINISH = 102;
    public static final int FAILED = 103;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                switch (msg.what) {
                    case START:
                        MyUtil.showProDialog(BaseActivity.getContext());
                        break;
                    case FINISH:
                        MyUtil.hidProDialog();
                        break;
                    case FAILED:
                        MyUtil.hidProDialog();
                        RxToast.error((String) msg.obj);
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}
